public class BinarySearchTree {
 //二叉搜说树代码实现
    static class TreeNode {
        public int key;
        public TreeNode left;
        public TreeNode right;
 
        TreeNode(int key) {
            this.key = key;
        }
    }
 
    public TreeNode root;
 
    /**
     * 插入一个元素
     * @param key
     */
    public boolean insert(int key) {
        if(root==null){
            root=new TreeNode(key);
        }
        TreeNode cur=root;
        TreeNode parent=null;
        while(cur!=null){
            if(cur.key<key){
                parent=cur;
                cur=cur.right;
            }else if(cur.key==key){
                return  true;
            }
            else{
                parent=cur;
                cur=cur.left;
            }
        }
        
        return true;
    }
    //查找key是否存在
    public TreeNode search(int key) {
        TreeNode cur=root;
        while(cur!=null){
            if(cur.key<key){
                cur=cur.right;
            }else if(cur.key==key){
                return cur;
            }else{
                cur=cur.left;
            }
        }
      
        return null;
    }
    //删除key的值
    public boolean remove(int key) {
        TreeNode cur = root;
        TreeNode parent = null;
        while (cur != null) {
            if(cur.key == key) {
                removeNode(parent,cur);
                return true;
            }else if(cur.key  < key) {
                parent = cur;
                cur = cur.right;
            }else {
                parent = cur;
                cur = cur.left;
            }
        }
        return false;
    }

    private void removeNode(TreeNode parent, TreeNode cur) {
        //1cur.left==null

        //cur为删除的结点，且cur是根结点，
        //
       if(cur.left==null){
           if(cur==root){
               root=root.right;
           }else if(parent.left==cur){//cur不是根节点
               parent.left=cur.right;
           }else{
               parent.right=cur.right;
           }
       }
       if(cur.right==null){
           if(cur==root){
               root=root.left;
           }else if(parent.left==null){
               parent.left=cur.left;
           }else{
               parent.right=cur.left;
           }
       }
       if(cur.left!=null&&cur.right!=null){
           //需要使用替换删除
           TreeNode target=cur.right;
           TreeNode targetP=cur;
           while(target.left!=null){
               targetP=target;
               target=target.left;
           }
           cur.key=target.key;
           if(target == targetP.left) {
               targetP.left = target.right;
           }else {
               targetP.right = target.right;
           }
       }
    }


}